import 'dart:math';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shishi/bean/tangshibean.dart';
import 'package:shishi/page/SearchXiangQing.dart';

import '../Colors.dart';

class Search extends StatefulWidget {
  @override
  _SearchState createState() => _SearchState();
}

class _SearchState extends State<Search> {

  List<Color> bgcolors = [
    Colors.red,
    Colors.greenAccent,
    Colors.pink,
    Colors.lightGreenAccent,
    Colors.green[200]
  ];

  List shiren = [
    '李白',
    '杜甫',
    '白居易',
    '孟浩然'
  ];

  String word;
  int page = 1;
  int num = 10;
  List<shi> _listshi = new List<shi>();
  TangShi tangShi;

  ScrollController scrollController = new ScrollController();
  TextEditingController _textEditingController = new TextEditingController();

  void GetSearch() async {
    try {
      Response response = await Dio().get(
          "http://api.tianapi.com/txapi/poetry/index?key=a69400da230d90d3d4ed644b6d3d1fb7&num=$num&page=$page&word=$word");

      tangShi = new TangShi(response.data);
      Fluttertoast.showToast(msg: '正在加载第$page页数据');
      if(tangShi.msg.endsWith('数据查询失败')) {
        Fluttertoast.showToast(msg: '没有数据');
      } else {
        _listshi.addAll(tangShi.newslist);
      }

      setState(() {});
      page++;
    } catch (e) {
      print(e);
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    scrollController.addListener(() {
      //翻页
      if (scrollController.position.pixels == scrollController.position.maxScrollExtent) {
        GetSearch();
      }
    });

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('搜索'),
      ),
      body:  Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(left: 5),
                width: MediaQuery.of(context).size.width * 0.8,
                child: TextField(
                  controller: _textEditingController,
                  textInputAction: TextInputAction.search,
                  onChanged: (v) {
                    word = v;
                  },

                  decoration: InputDecoration(
                      fillColor: Colors.pink,
                      suffixIcon: IconButton(
                        icon: Icon(Icons.close),
                        onPressed: () {
                          page=1;
                          _textEditingController.clear();
                        },
                      )
                  ),
                ),
              ),
              Expanded(
                child: IconButton(
                  icon: Icon(Icons.search),
                  color: Cos.zhutise,
                  onPressed: () {

                  },
                ),
              )
            ],
          ),
          body()
        ],
      ),
    );
  }

  Widget body() {
    if(_listshi.length > 1) {
      return  Expanded(
        child: ListView.builder(
          controller: scrollController,
          itemCount: _listshi.length,
          itemBuilder: (context,index) {
            return  Card(
                elevation: 5,
                child: ListTile(
                  title: Text('${_listshi[index].title}'),
                  subtitle: Text("${_listshi[index].content}"),
                  trailing: Text("${_listshi[index].author}"),
                  onTap: () {
                    Navigator.of(context).push(
                        CupertinoPageRoute(builder: (context){
                          return SearchXiangQing(
                            title: _listshi[index].title,
                            content: _listshi[index].content,
                            author: _listshi[index].author,
                            kind: _listshi[index].kind,
                            intro: _listshi[index].intro,
                          );
                        })
                    );
                  },
                ),
            );
          },
        ),
      );
    } else {
      return Wrap(
        alignment: WrapAlignment.start,
        children: interestsWidgets.toList(),
      );
    }
  }

  Iterable<Widget> get interestsWidgets sync* {
    for (int i = 0; i < shiren.length; i++) {
      yield Container(
          margin: EdgeInsets.only(left: 10),
          decoration: BoxDecoration(borderRadius: BorderRadius.circular((10))),
          child: GestureDetector(
            child: Chip(
              backgroundColor: bgcolors[Random().nextInt(bgcolors.length)],
              label: Text(
                '${shiren[i]}',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                ),
              ),
              labelPadding: EdgeInsets.only(left: 10.0, right: 10.0),
              materialTapTargetSize: MaterialTapTargetSize.padded,
            ),
            onTap: () {
              word = shiren[i];
              GetSearch();
            },
          )
      );
    }
  }


  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    scrollController.dispose();
    _textEditingController.dispose();
  }

}
